/*
 * Copyright 2004 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jbfilter.impl;

import java.util.Collection;
import java.util.EnumMap;

import org.jbfilter.bean.FilterComponentBean;
import org.jbfilter.core.FilterComponent;
import org.jbfilter.core.fcomps.logic.Logic;

/**
 * The filter logic (behavior) for and, or, xor bean filtering.
 * Sorry for the "if else if else if else switch switch" developers : my inner geek loves this design...
 * @author Marcus Adrian
 *
 */
enum _LogicBean {
	and(Logic.and) {
		@Override
		<E> boolean passCallBack(E bean, Collection<FilterComponent<E>> filterComponents) {
			for (FilterComponent<E> fcomp : filterComponents) {
				if (!fcomp.isActive()) {
					continue;
				}
				if (!pass(fcomp, bean)) {
					return false;
				}
			}
			return true;
		}
	},
	or(Logic.or) {
		@Override
		<E> boolean passCallBack(E bean, Collection<FilterComponent<E>> filterComponents) {
			for (FilterComponent<E> fcomp : filterComponents) {
				if (!fcomp.isActive()) {
					continue;
				}
				if (pass(fcomp, bean)) {
					return true;
				}
			}
			return false;
		}
	},
	xor(Logic.xor) {
		@Override
		<E> boolean passCallBack(E bean, Collection<FilterComponent<E>> filterComponents) {
			int passCpt = 0;
			for (FilterComponent<E> fcomp : filterComponents) {
				if (!fcomp.isActive()) {
					continue;
				}
				if (pass(fcomp, bean)) {
					if (++passCpt > 1) {
						return false;
					}
				} 
			}
			return passCpt == 1;
		}
	};
	
	private Logic logic;
	private static final EnumMap<Logic, _LogicBean> logic2LogicBean = new EnumMap<Logic, _LogicBean>(Logic.class);
	static {
		for (_LogicBean logicBean : _LogicBean.values()) {
			logic2LogicBean.put(logicBean.logic, logicBean);
		}
	}
	private static <E> boolean pass(FilterComponent<E> fcomp, E bean) {
		// the class which uses this enum must make sure that this casts works fine
		return ((FilterComponentBean<E>)fcomp).pass(bean);
	}
	public static _LogicBean fromLogic(Logic logic) {
		return logic2LogicBean.get(logic);
	}
	private _LogicBean(Logic logic) {
		 this.logic = logic;
	}
	abstract <E> boolean passCallBack(E bean, Collection<FilterComponent<E>> filterComponents);
	
	public Logic getLogic() {
		return logic;
	}
}
